package com.edoomath.api.servcice.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.edoomath.api.dao.UserCourseTaskDao;
import com.edoomath.api.servcice.UserCourseTaskMediaService;
import com.edoomath.entity.course.UserCourseTaskMedia;
import com.edoomath.entity.usercourse.ProgressStatus;
import com.edoomath.entity.usercourse.UserCourseTask;

/**
 * 
 * @author mohanlan
 *
 */
@Service("userCourseTaskMediaService")
public class UserCourseTaskMediaServiceImpl implements UserCourseTaskMediaService {
	
	@Autowired
	private GenericDaoSupport genericDaoSupport;
	
	@Dao
	private UserCourseTaskDao userCourseTaskDao;

	@Override
	public void init() {
		
		List<UserCourseTask> tasks = userCourseTaskDao.list(ProgressStatus.FINISHED);
		
		for(UserCourseTask task : tasks) {
			
			String imgs = task.getImages();
			if(StringUtils.isNoneBlank(imgs)) {
				
				List<UserCourseTaskMedia> medias = userCourseTaskDao.listUserCourseTaskMedia(task, "PHOTO");
				for(UserCourseTaskMedia media : medias) {
					genericDaoSupport.save(media.disable());
				}
				
				String[] images = imgs.split(",");
				for(String image : images) {
					UserCourseTaskMedia media = new UserCourseTaskMedia(task, image);
					genericDaoSupport.save(media.init());
				}
			}
			
			String audios = task.getRadios();
			if(StringUtils.isNoneBlank(audios)) {
				
				List<UserCourseTaskMedia> medias = userCourseTaskDao.listUserCourseTaskMedia(task, "AUDIO");
				for(UserCourseTaskMedia media : medias) {
					genericDaoSupport.save(media.disable());
				}
				
				UserCourseTaskMedia media = new UserCourseTaskMedia(task, audios, task.getRadioSeconds());
				genericDaoSupport.save(media.init());
			}
			
			
		}
		
	}

}
